<?php
/**
 * 登录授权Service
 * Date: 2025/08/31
 */

namespace App\Services\Admin;

use App\Cache\CheckVerifyCache;
use App\libraries\Captcha\VerifyCode;
use App\Models\AdminModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\Auth;

class AuthService extends BaseService
{
    /**
     * 获取登录验证码
     * @date 2025/08/31
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifyCode()
    {
        // 获取验证码
        $data = (new VerifyCode())->getVerifyCode();

        // 缓存验证码
        (new CheckVerifyCache(['admin_login', $data['token']]))->set($data['code'], config('project.verify_code_expire'));

        return $this->success([
            'token' => $data['token'],
            'base64' => $data['base64'],
            'expire' => config('project.verify_code_expire')
        ], '获取验证码成功');
    }

    /**
     * 管理员登录
     * @date 2025/08/31
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function login($params)
    {
        try {
            // 管理员登录授权检测
            $adminInfo = $this->loginCheck(['account' => $params['account']]);

            // 管理员密码错误
            if (!password_verify($params['password'], $adminInfo->password)) {
                return $this->failed('密码错误');
            }

            // 验证码校验
            $redisCode = (new CheckVerifyCache(['admin_login', $params['token']]))->get();
            if ($params['code'] != $redisCode) {
                return $this->failed('验证码错误');
            }

            // 登录获取token
            $token = Auth::guard('admin')->login($adminInfo);

            // 更新管理员登录信息
            $updateResult = AdminModel::query()->where('id', $adminInfo->id)->update([
                'last_ip' => request()->ip(),
                'last_time' => date('Y-m-d H:i:s')
            ]);
            if (!$updateResult) {
                return $this->failed('登录失败');
            }
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage(), $exception->getCode());
        }

        // 返回信息
        return $this->success([
            'token' => "Bearer " . $token,
            'userinfo' => (new MyService())->getMyInfo($adminInfo->id)
        ]);
    }

    /**
     * 管理员退出登录
     * @date 2025/08/31
     * @param int $adminInfo 管理员信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut()
    {
        // 退出登录
        Auth::guard('admin')->logout();

        // 返回信息
        return $this->success();
    }

    /**
     * 登录授权的管理员检测
     * @date 2025/08/31
     * @param array $adminWhere 可以查出唯一数据的用户条件
     * @return mixed
     * @throws \Exception
     */
    public function loginCheck($adminWhere)
    {
        // 查询管理员信息
        $adminInfo = AdminModel::query()->where($adminWhere)->first();
        if (empty($adminInfo)) {
            return $this->failed('管理员信息不存在', 401);
        }
        if ($adminInfo->status == AdminModel::STATUS_CLOSE) {
            return $this->failed('当前管理员已被禁用', 401);
        }
        return $adminInfo;
    }
}
